namespace RBAC.Read.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.BomCommand;

    /// <summary>
    /// 产品分页查询处理器（无条件）
    /// </summary>
    public class GetProductPageHandler : IRequestHandler<GetProductPageCommand, APIPaging<Product>>
    {
        private readonly IBaseRepository<Product> repository;
        private readonly ILogger<GetProductPageHandler> logger;

        public GetProductPageHandler(IBaseRepository<Product> repository, ILogger<GetProductPageHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理 产品 无条件分页查询请求。
        /// - 校验页码与页大小
        /// - 支持取消
        /// - 分别处理取消异常与一般异常
        /// </summary>
        /// <param name="request">分页请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public Task<APIPaging<Product>> Handle(GetProductPageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<Product>();
            try
            {
                // 取消检查（尽早返回）
                cancellationToken.ThrowIfCancellationRequested();

                // 基础参数校验与兜底
                if (request.PageIndex <= 0) request.PageIndex = 1;
                if (request.PageSize <= 0) request.PageSize = 10;

                logger.LogInformation("开始获取产品分页 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                var (data, total) = repository.GetPaged(request.PageIndex, request.PageSize, string.Empty, request.OrderBy, null);

                result.Code = APIEnums.Success;
                result.PageDatas = data;
                result.TotalCount = total;
                result.Msg = "获取产品分页成功";
            }
            catch (OperationCanceledException)
            {
                logger.LogWarning("获取产品分页被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.PageDatas = new List<Product>();
                result.TotalCount = 0;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取产品分页失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取产品分页失败";
                result.PageDatas = new List<Product>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }
    }
}
